package org.hejw.rpc.discovery;

import com.alibaba.fastjson.JSON;
import org.I0Itec.zkclient.ZkClient;
import org.hejw.rpc.info.ServiceInfo;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class ZookeeperServiceInfoDiscoverer implements ServiceInfoDiscoverer {

    ZkClient client;

    private String centerRootPath = "/rpc-zz";

    public ZookeeperServiceInfoDiscoverer() {
        String address = "127.0.0.1:2181";
        this.client = new ZkClient(address);
        client.setZkSerializer(new DefaultZkSerializer());
    }

    /**
     * 从zookeeper上读取服务端的信息，包括 服务名称、协议、服务端地址；
     * @param serviceName
     * @return
     */
    public List<ServiceInfo> getServiceInfo(String serviceName) {
        String servicePath = centerRootPath + "/" + serviceName + "/service";
        List<String> children = client.getChildren(servicePath);
        List<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>();
        for (String child : children) {
            try {
                String decode = URLDecoder.decode(child, "UTF-8");
                ServiceInfo r = JSON.parseObject(decode, ServiceInfo.class);
                serviceInfos.add(r);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return serviceInfos;
    }
}
